﻿using System.Collections;
using System.Collections.Generic;
using Microsoft.SharePoint;
using System.Modules.SharePoint.Constants;
using System.Text;

namespace System.Modules.SharePoint.Contracts.DTO
{
    /// <summary>
    /// Use to populate SP Query Value Tag
    /// </summary>
    public class SPQueryValue
    {
        #region Properties
        /// <summary>
        /// SPFieldType
        /// </summary>
        public SPFieldType? FieldType { get; set; }
        /// <summary>
        /// String value
        /// </summary>
        public string Value { get; set; }

        /// <summary>
        /// IncludeTimeValue
        /// </summary>
        public bool? IncludeTimeValue { get; set; }

        /// <summary>
        /// Other Attributes
        /// </summary>
        public List<DictionaryEntry> Attributes { get; set; }
        #endregion

        #region Constructor
        /// <summary>
        /// Default Constructor
        /// </summary>
        public SPQueryValue() { }

        /// <summary>
        /// Initiate a SP Query Value object
        /// </summary>
        /// <param name="type"></param>
        /// <param name="value"></param>
        public SPQueryValue(SPFieldType type, string value)
        {
            FieldType = type;
            Value = value;
        }
        #endregion

        #region Implicit Operators
        /// <summary>
        /// Implicit conversion operator to string
        /// </summary>
        /// <param name="value">The SP Query Value</param>
        /// <returns>A string representation of the object</returns>
        public static implicit operator string(SPQueryValue value)
        {
            return value == null ? string.Empty : value.ToString();
        }
        #endregion

        #region Override
        /// <summary>
        /// Overrides To String
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            var value = new StringBuilder();
            //Build Attributes
            if(FieldType.HasValue)
            {
                value.AppendFormat(SPQueryTemplateAttributes.TYPE, FieldType);
            }
            if (IncludeTimeValue.HasValue)
            {
                value.AppendFormat(SPQueryTemplateAttributes.INCLUDE_TIME_VALUE, IncludeTimeValue.Value.ToString().ToUpper());
            }
            if (Attributes != null)
            {
                foreach (var dictionaryEntry in Attributes)
                {
                    value.AppendFormat(SPQueryTemplateAttributes.DEFAULT, dictionaryEntry.Key, dictionaryEntry.Value);
                }
            }
            return String.Format(SPQueryTemplates.VALUE, value, Value);
        }
        #endregion
    }
}
